package com.bungarus.busi;

import io.lettuce.core.ClientOptions;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.api.StatefulRedisConnection;

import java.security.InvalidKeyException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.function.Consumer;

abstract public class RedisStorage<K, T> {
    protected StatefulRedisConnection<String, String> connection;
    public RedisStorage() {
        init();
    }

    private void init() {
        RedisURI uri = RedisURI.create(storageUrl());
        uri.setDatabase(storageDbNumber());
        uri.setTimeout(Duration.of(storageConnectionTimeout(), ChronoUnit.MILLIS));

        RedisClient redisClient = RedisClient.create(uri);
        redisClient.setOptions(ClientOptions.builder()
                .autoReconnect(true)
                .pingBeforeActivateConnection(true)
                .socketOptions(SocketOptions.builder().tcpNoDelay(true).build())
                .build());
        connection = redisClient.connect();
    }

    abstract public String storageUrl();
    abstract public Integer storageDbNumber();
    abstract public Integer storageConnectionTimeout();

    abstract public String makeKey(T entity);

    abstract public void storeEntity(K key, String field, T entity);
    abstract public T retrieveEntity(K key, String field);
}
